<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>键盘事件 keypress 和 keydown</title>
    <style>
        code {
            margin: 5px;
        }
    </style>
</head>
<body>
    <p>大家敲敲键盘试试，别忘了上下左右键</p>
    <p><input id="text" autofocus type="text"></p>
    <p><code>keypress</code>的<code>charCode</code>：<span id="keypress"></span></p>
    <p><code>keydown</code>的<code>charCode</code>：<span id="keydown"></span></p>

    <script>
        /**
         * 修复事件对象不兼容的地方
         */
        function fixEventObj(e) {
            e.target = e.target || e.srcElement;
            e.preventDefault = e.preventDefault || function () {
                    e.returnValue = false;
                };
            e.stopPropagation = e.stopPropagation || function () {
                    e.cancelBubble = true;
                };

            return e;
        }

        /**
         * 跨浏览器的绑定事件
         */
        function on(elem, type, handle) {
            if (elem.addEventListener) { // 检测是否有标准方法
                elem.addEventListener(type, handle, false);
            } else if (elem.attachEvent) { // 试图使用 `attachEvent`
                elem.attachEvent('on' + type, function (event) {
                    event = fixEventObj(event);
                    handle.call(elem, event); // 使用 call 来改变 handle 的作用域，使其指向 elem
                });
            } else { // 兜底
                elem['on' + type] = function () {
                    var event = fixEventObj(window.event);
                    handle.call(elem, event);
                }
            }
        }

        var keypress = document.getElementById('keypress');
        var keydown = document.getElementById('keydown');
        var text = document.getElementById('text');

        on(text, 'keypress', function(e) {
            console && console.log('keypress', e);
            keypress.innerHTML = e.keyCode;
        });

        on(text, 'keydown', function(e) {
            console && console.log('keydown', e);
            keydown.innerHTML = e.keyCode;
        });
    </script>
</body>
</html>